//
//  AY_BookShelfViewController.m
//  AiYue
//
//  Created by mac on 2023/10/16.
//

#import "AY_BookShelfViewController.h"
#import "AY_BookSelfHeaderView.h"
#import "AY_BookSelfCell.h"
#import "AY_MainTabViewController.h"
#import "AY_SearchViewController.h"
#import "AY_BookRecommendModel.h"
#import "AY_RecommendView.h"
#import "AY_BookDetailViewController.h"
#import "AppDelegate.h"
#import "AY_BookQianDPage.h"
@interface AY_BookShelfViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (strong,nonatomic) UICollectionView *collectionView;
@property (strong,nonatomic) NSMutableArray *dataSource;
@property (strong,nonatomic) UIView *searchView;
@property (strong,nonatomic) UIView *searchView1;
@property (strong,nonatomic) AY_BookSelfHeaderView *headerView;
@property (strong,nonatomic) AY_RecommendView *recommendView;
@property (nonatomic, strong) UIButton * qdBtn;
@end

@implementation AY_BookShelfViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.collectionView];
    [self.gk_navigationBar addSubview:self.searchView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recommendRefreTask) name:REFRECommend object:nil];
}

- (void)qiandaoWithAction {
    AY_BookQianDPage * vc = [[AY_BookQianDPage alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)getData {
    AppDelegate *appD = [UIApplication sharedApplication].delegate;
    if (!appD.isShowAd) {
       [self recommendTasknovel];
    }else{
        appD.isShowAd = NO;
    }
   
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    [AYApiRequest getBookSelfListSuccess:^(AY_BookSelfModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        self.dataSource = [NSMutableArray arrayWithArray:pkg.data];
        self.headerView.dataAry = self.dataSource;
        self.headerView.shelfVc = self;
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest getTodayReadTimeSuccess:^(AY_TodayReadTimeModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        self.headerView.readTime = pkg.data;
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];
    });
}

- (void)recommendRefreTask
{
    [self recommendTasknovel];
}
- (void)recommendTasknovel
{
    [AYApiRequest recommendTaskNovelWithSuccess:^(AY_BookRecommendModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            BookRecommendModel *model = pkg.data;
            if (model) {
                self.recommendView.recommendModel = model;
                NSString *recommemdId = [AYMMKV getStringForKey:Recommend];
                if(recommemdId&&[recommemdId isEqualToString:model.recommendId]){
                }else{
                    [self.recommendView showPopView];
                    [AYMMKV setString:model.recommendId forKey:Recommend];
                }
            }
        }
    } failure:^(int status, NSString * _Nonnull info) {
        
    }];
}
#pragma mark - search
- (void)search {
    AY_SearchViewController *searchVC = [[AY_SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark -- UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count == 0 ? 1 : self.dataSource.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    AY_BookSelfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AY_BookSelfCell" forIndexPath:indexPath];
    bool isLast = self.dataSource.count == 0 ? true : indexPath.row == self.dataSource.count ? true : false;
    BookSelfModel *model = [[BookSelfModel alloc] init];
    if (!isLast) {
        model = self.dataSource[indexPath.row];
    }
    [cell sendBookSelfModel:model andIsLast:isLast];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        self.headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"AY_BookSelfHeaderView" forIndexPath:indexPath];
        if (self.dataSource.count > 0) {
            self.headerView.hidden = NO;
            self.headerView.model = self.dataSource[0];
        }else {
            self.headerView.hidden = YES;
        }
        return self.headerView;
    }else {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        return footerView;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataSource.count == 0 || indexPath.row == self.dataSource.count) {
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        UINavigationController *nav = (UINavigationController *) window.rootViewController;
        AY_MainTabViewController *rootViewController = nav.viewControllers[0];
        [rootViewController setSelectedIndex:1];
    }else {
        AY_PageReadViewController *vc = [[AY_PageReadViewController alloc] init];
        BookSelfModel *model = self.dataSource[indexPath.row];
        [vc sendBookId:model.articleId andPage:[NSString stringWithFormat:@"%ld",model.pageNo.integerValue - 1] andChapterIndex:[NSString stringWithFormat:@"%ld",model.chapterNo.integerValue - 1]];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (self.dataSource.count > 0) {
        return CGSizeMake(SCREEN_W, YNUM(150));
    }else {
        return CGSizeMake(SCREEN_W, 0.001);
    }
}

#pragma mark - init
-(AY_BookSelfHeaderView *)headerView {
    if (!_headerView) {
        AY_BookSelfHeaderView *headerView = [[AY_BookSelfHeaderView alloc] init];
        _headerView = headerView;
    }
    return _headerView;
}

- (UIView *)searchView {
    if (!_searchView) {
        UIView *searchView = [AYTool createViewWithFrame:CGRectMake(0, 0, SCREEN_W, GK_NAVBAR_HEIGHT) andBg:nil andRadius:YNUM(16) andAddSubView:self.view];
        self.searchView1 = [[UIView alloc] initWithFrame:CGRectMake(YNUM(16), YNUM(3), searchView.width - YNUM(96) - YNUM(16), YNUM(34))];
        
        if ([AYMMKV getBoolForKey:ISSHENHE defaultValue:YES]) {
            self.searchView1.width = searchView.width - YNUM(16) - YNUM(16);
        }
        
        self.searchView1.backgroundColor = COLOR(@"EAEEF7");
        self.searchView1.layer.masksToBounds = YES;
        self.searchView1.layer.cornerRadius = YNUM(17);
        [searchView addSubview:self.searchView1];
        
        UIImageView *icon = [AYTool createImageViewWithFrame:CGRectZero andImage:YImage(@"AY_search_icon") andBg:nil andRadius:0 andAddSubView:self.searchView1];
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.searchView1).offset(YNUM(12));
            make.centerY.equalTo(self.searchView1);
            make.width.height.mas_equalTo(YNUM(16));
        }];
        UILabel *info = [AYTool createLabelWithFrame:CGRectZero andText:@"搜索书名、作者" andTextColor:COLOR(@"#8A8E97") andBgColor:nil andFont:YFont(14) andLines:1 andRadius:0 andAddSubView:searchView];
        [info mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(icon.mas_right).offset(YNUM(8));
            make.centerY.equalTo(self.searchView1);
        }];
        
        UIButton *btn = [[UIButton alloc] initWithFrame:self.searchView1.bounds];
        [btn addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
        [self.searchView1 addSubview:btn];
        
        self.qdBtn = [AYTool createButtonWithFrame:CGRectMake(SCREEN_W - YNUM(86), YNUM(3), YNUM(71), YNUM(34)) andTitle:@"" andFont:nil andTitleColor:nil andBg:nil andImage:nil andBgImage:YImage(@"icon_qiand.png") andTarget:self andAction:@selector(qiandaoWithAction) andRadius:0 andAddSubView:searchView];
        self.qdBtn.hidden = YES;
        if (![AYMMKV getBoolForKey:ISSHENHE defaultValue:YES]) {
            self.qdBtn.hidden = NO;
        }
        _searchView = searchView;
    }
    return _searchView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake((SCREEN_W - YNUM(100))/3, YNUM(190));
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.sectionInset = UIEdgeInsetsMake(0, YNUM(20), 0, YNUM(20));
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_W, SCREEN_H - GK_STATUSBAR_NAVBAR_HEIGHT - GK_TABBAR_HEIGHT) collectionViewLayout:layout];
        _collectionView.dataSource = self;
//        _collectionView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        [_collectionView registerClass:[AY_BookSelfCell class] forCellWithReuseIdentifier:@"AY_BookSelfCell"];
        [_collectionView registerClass:[AY_BookSelfHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"AY_BookSelfHeaderView"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    }
    return _collectionView;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (AY_RecommendView *)recommendView {
    if(!_recommendView) {
        _recommendView = [[AY_RecommendView alloc] initWithFrame:CGRectMake(0, 0, GK_SCREEN_WIDTH, GK_SCREEN_HEIGHT)];
        Weak_Self
        _recommendView.readBlock = ^(NSString *artId){
            AY_BookDetailViewController *bookDetailVC = [[AY_BookDetailViewController alloc] init];
            bookDetailVC.bookId = artId;
            [self.navigationController pushViewController:bookDetailVC animated:YES];
        };
    }
    return _recommendView;
}

@end
